var winston = require('winston');
var gm = require('gm');
var defaultBorderWidth = 10;
var defaultBorderColor = '#ffffff';

module.exports = function(req, res, next){
	var content = req.params.content;
	var width = Number.from(req.query.borderWidth) || defaultBorderWidth;
	var color = req.query.borderColor || defaultBorderColor;
	var queryString = [];
	if(req.query.width){
		queryString.push('width=' + req.query.width);
	}
	if(req.query.darkColor){
		queryString.push('darkColor=' + encodeURIComponent(req.query.darkColor));
	}
	if(req.query.lightColor){
		queryString.push('lightColor=' + encodeURIComponent(req.query.lightColor));
	}

	content = encodeURIComponent(content);
	var qr = req.protocol + "://" + req.hostname + "/qr/" + content + "?" + queryString.join('&');
	gm(qr)
		.command('convert')
		.in('-border', width)
		.in('-bordercolor', color)
		.toBuffer('PNG',function (err, buffer) {
		  if (err) {
		  	winston.error(err);
		  	res.end();
		  } else {
		  	res.set('Content-Type', 'image/png');
				res.send(buffer);
		  }
		  
		});

}